
import { isNumber, asNumber, argsAnd } from '../../utils/common';

export const dashboardFilter = {
  params ({ pid }) {
    return { pid };
  },
  views ({
    sales,
    vips,
    flows,
    brands
  }) {
    sales = sales.result || {};
    // avg_sum: "360.00"
    // list: (3) [{…}, {…}, {…}]
    // sell_num: 3
    // sun_amount: 1080
    vips = vips.result || {};
    // last_month_vip: 0
    // last_week_vip: 0
    // list: (15) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
    // month_grow: 0
    // month_same_ratio: "0"
    // month_surround_ratio: "0.00"
    // month_vip: 0
    // week_grow: 0
    // week_same_ratio: "0"
    // week_surround_ratio: "0.00"
    // week_vip: 0
    flows = flows.result || {};
    // last_car_in: 0
    // last_car_list: (15) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
    // last_person_in: 0
    // last_person_list: (15) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
    // now_car_in: 0
    // sum_person_in: 0
    brands = brands.result || {};
    // bad_list: (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
    // good_list: (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
    // not_check: 0
    // not_check_list: []
    // not_check_ratio: "0.00"
    // not_sub: 18
    // not_sub_list: (18) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
    // not_sub_ratio: "100.00"
    // sum_sales: "12603257.40"
    // sum_sales_last: 0
    // sum_sales_last_same_ratio: "0.00"
    // sum_sales_last_surround_ratio: "0.00"
    // sum_sales_last_unit: "0.00"
    // sum_sales_last_unit_same_ratio: "0.00"
    // sum_sales_last_unit_surround_ratio: "0.00"
    // sum_sales_list_last: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
    // sum_sales_list_now: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
    // sum_sales_month: 0
    // sum_sales_month_same_ratio: "0.00"
    // sum_sales_month_surround_ratio: "0.00"
    // sum_sales_same_ratio: "0.00"
    // sum_sales_surround_ratio: "0.00"
    // sum_sales_week: 0
    // sum_sales_week_same_ratio: "0.00"
    // sum_sales_week_surround_ratio: "0.00"


    // 今日经营情况
    const todaySummaryVO = {
      tradingVolume: Math.ceil(sales.sun_amount/10000),
      tradingCount: Math.ceil(sales.sell_num/1),
      unitPrice: Math.ceil(sales.avg_sum/1),
      carCount: flows.now_car_in,
      customerCount: flows.now_person_in || '0',
      inCustomerCount: flows.sum_person_in
    }

    // 今日销售情况
    const salesData = [];
    if (sales && sales.list) {
      for (const idx in sales.list) {
        const obj = sales.list[idx];
  
        salesData.push({
          key: Math.random(1000),
          time: obj.occur_time,
          shop: obj.shop_name,
          memberId: obj.vip_name,
          amount: obj.amount
        });
      }
    }
    
    const todaySalesVO = {
      data: salesData
    };

    // 会员趋势
    const vipsTrendData = [];
    let vipsTrendVO = {data:vipsTrendData};
    if (vips && vips.list) {
      for (const idx in vips.list) {
        const obj = vips.list[idx];
  
        var timestamp = Date.parse(obj.time); // "yyyy/MM/dd"
        var date = new Date(timestamp);
        var month = date.getMonth()+1
        var MM_DD = month +'.'+date.getDate();
        vipsTrendData.push({
          x: MM_DD,
          y: obj.count
        });
      }

      vipsTrendVO = {
        weekAddCount: vips.week_grow,
        weekTb: vips.week_same_ratio+'%',
        weekHb: vips.week_surround_ratio+'%',
        weekGrow: vips.week_grow > vips.last_week_vip,
        monthAddCount: vips.month_grow,
        monthTb: vips.month_same_ratio+'%',
        monthHb: vips.month_surround_ratio+'%',
        monthGrow: vips.month_grow > vips.last_month_vip,
        data: vipsTrendData,
      };
    }
    
    

    // 销售报警
    let salesWarnVO = {};
    if (brands && brands.not_sub_list) {
      const salesWarnTable = [];
      for (const idx in brands.not_sub_list) {
        const obj = brands.not_sub_list[idx];

        salesWarnTable.push(obj.name);
      }

      salesWarnVO = {
        notReportCount: brands.not_sub,
        notReportPercent: Math.ceil(brands.not_sub_ratio),
        notReviewCount: brands.not_check,
        notReviewPercent: Math.ceil(brands.not_check_ratio),
        table: salesWarnTable
      };
    }

    // 上榜品牌
    const salesTopList = [];
    if (brands && brands.good_list) {
      for (const idx in brands.good_list) {
        const obj = brands.good_list[idx];
        salesTopList.push({
          key: Math.random(1000),
          rank: parseInt(idx)+1,
          merchantName: obj.brand_name,
          amount: obj.sales_num,
          unitPrice: Math.ceil(obj.unit_price)
        });
      }
    }
  
    const salesTopVO = {
      list: salesTopList
    };

    // 倒数品牌
    const salesBottomList = [];
    if (brands && brands.bad_list) {
      for (const idx in brands.bad_list) {
        const obj = brands.bad_list[idx];
        salesBottomList.push({
          key: Math.random(1000),
          rank: parseInt(idx)+1,
          merchantName: obj.brand_name,
          amount: obj.sales_num,
          unitPrice: Math.ceil(obj.unit_price)
        });
      }
    }

    const salesBottomVO = {
      list: salesBottomList
    };

    // 销售额趋势
    const xData = [];
    var saleData = [];
    const compareData = [];
    /**
     * 特殊操作
     *
     * 1。 服务器 返回20个点
     * 2。 前端多退少补，显示15个点
     * 3。 当月前缀如果有31号，则上月补31-0
     * 4。 当月前缀如果有30号，则上月去31
     * 5。 最特殊的是2月份了
     *
     * @param dates [ '07.30', '07.31', '08.01', '08.02']
     * @param x1s [ '1' ]
     * @param x2s [ '2' ]
     */
    function getDaysOfMonth (year, month) {
      var d = new Date(year, month, 0);
      return d.getDate();
    }
    function getLastMonthByCur (curMonth) {
      if (curMonth == 1) return 12;
      return curMonth-1;
    }
    function rearrangeSales(dates, x1s, x2s, year) { // x1s 是当月
      var VALID_LENGTH = 15, MIN_LENGTH = 20;

      var length = dates.length;
      if (dates != null && length >= MIN_LENGTH) {
        var lastDay = dates[length-1];

        var daySplits = lastDay.split('.');
        var month = parseInt(daySplits[0]);
        var day = parseInt(daySplits[1]);

        var lastMonth = getLastMonthByCur(month);
        var lastLastMonth = getLastMonthByCur(lastMonth);

        var lastMonthDays = getDaysOfMonth(year, lastMonth);
        var lastLastMonthDays = getDaysOfMonth(year, lastLastMonth);

        if (day >= VALID_LENGTH ||
          lastMonthDays == lastLastMonthDays) {
          // slice last 15
        } else {
          // 保留 后 day 个点
          if (lastMonthDays < lastLastMonthDays) {
            var delta = lastLastMonthDays - lastMonthDays;

            // 先删减，再slice
            x2s.splice(length - day - delta, delta);
          } else if (lastMonthDays > lastLastMonthDays) {
            var delta = lastMonthDays - lastLastMonthDays;

            // 先插入，再slice
            while (delta --) {
              x2s.splice(length - day, 0, '0.00');
            }
          }
        }

        return {
          dates: dates.slice(length - VALID_LENGTH),
          x1s: x1s.slice(length - VALID_LENGTH),
          x2s: x2s.slice(length - VALID_LENGTH)
        };
      }

      return {
        dates: dates,
        x1s: x1s,
        x2s: x2s
      }
    }
    var year = 2019;

    if (brands && brands.sum_sales_list_now) {
      for (const idx in brands.sum_sales_list_now) {
        const obj = brands.sum_sales_list_now[idx];
  
        if (!isNumber(obj.value)) obj.value = 0;
        var value = obj.value/10000;
        value = value.toFixed(2);
  
        saleData.push(value);
  
        var times = obj.time.split('-');
  
        obj.time = times[1]+'-'+times[2];
  
        xData.push(obj.time);
  
        year = parseInt(times[0]);
      }
    }

    // 上个月
    if (brands && brands.sum_sales_list_last) {
      for (const idx in brands.sum_sales_list_last) {
        const obj = brands.sum_sales_list_last[idx];
  
        if (!isNumber(obj.value)) obj.value = 0;
  
        var value = obj.value/10000;
        value = value.toFixed(2);
  
        compareData.push(value);
      }
    }
    

    saleData = rearrangeSales(xData, saleData, compareData, year); // 重排
    const salesTrendList = [];
    for (const idx in saleData.dates) {
      salesTrendList.push({
        x: saleData.dates[idx],
        y1: saleData.x1s[idx],
        y2: saleData.x2s[idx],
      });
    }

    const salesTrendVO = {
      amount: asNumber(asNumber(brands.sum_sales)/10000),
      tb: asNumber(brands.sum_sales_last_same_ratio)+'%',
      hb: asNumber(brands.sum_sales_last_surround_ratio)+'%',
      data: salesTrendList,
    };

    // 销售额汇总
    if (!isNumber(brands.sum_sales_last)) brands.sum_sales_last = 0;
    if (!isNumber(brands.sum_sales_month)) brands.sum_sales_month = 0;
    if (!isNumber(brands.sum_sales_week)) brands.sum_sales_week = 0;
    if (!isNumber(brands.sum_sales_last_unit)) brands.sum_sales_last_unit = 0;
    const salesSummaryVO = {
      list: [
        // 累计月业绩
        {
          id: '1',
          label: '累计月业绩',
          percent: 20,
          color: '#4072EE',
          total: (asNumber(brands.sum_sales_month)/10000).toFixed(2)+'万元',
          tb: asNumber(brands.sum_sales_month_same_ratio)+'%',
          hb: asNumber(brands.sum_sales_month_surround_ratio)+'%',
        },
        // 累计周业绩
        {
          id: '2',
          label: '累计周业绩',
          percent: 90,
          color: '#F65860',

          total: (asNumber(brands.sum_sales_week)/10000).toFixed(2)+'万元',
          tb: asNumber(brands.sum_sales_week_same_ratio)+'%',
          hb: asNumber(brands.sum_sales_week_surround_ratio)+'%',
        },
        // 昨日业绩
        {
          id: '3',
          label: '昨日业绩',
          percent: 40,
          color: '#02D8FF',

          total: asNumber(brands.sum_sales_last)+'元',
          tb: asNumber(brands.sum_sales_same_ratio)+'%',
          hb: asNumber(brands.sum_sales_surround_ratio)+'%',
        },
        // 昨日客单价
        {
          id: '4',
          label: '昨日客单价',
          percent: 70,
          color: '#F8AD3A',

          total: asNumber(brands.sum_sales_last_unit)+'元',
          tb: asNumber(brands.sum_sales_last_unit_same_ratio)+'%',
          hb: asNumber(brands.sum_sales_last_unit_surround_ratio)+'%',
        },
      ]
    };

    // 客流量
    var xMaxData = 0;
    var xDatas = [], yDatas = [];
    function calNearMax (maxNum) {
      var maxNumStr = maxNum+'';
      var numArr = maxNumStr.split('');
      var max = parseInt(numArr[0]);
      max += 1;
      return max * Math.pow(10, numArr.length-1);
    }
    const personDataList = [];
    for (const idx in flows.last_person_list) {
      const obj = flows.last_person_list[idx];

      // 限制数据条目为15条
      if (parseInt(idx) > 15) return;

      if (typeof obj.in_sum == 'string') obj.in_sum = parseInt(obj.in_sum);
      if (obj.in_sum > xMaxData) xMaxData = obj.in_sum;

      personDataList.push({
        x: obj.flow_date_format,
        y: obj.in_sum
      }); // for biz charts

      // for echarts
      yDatas.push(obj.flow_date_format);
      xDatas.push(obj.in_sum);
    }

    // for biz charts
    const personDataList2 = [];
    for (const idx in personDataList) {
      const obj = personDataList[idx];
      personDataList2.push({
        x: obj.x,
        percent: obj.y/xMaxData
      });
    }

    const personsTrendVO = {
      num: flows.last_person_sun || '0',
      count: flows.last_person_in || "0",
      tb: asNumber(flows.last_person_same_ratio)+'%',
      hb: asNumber(flows.last_person_surround_ratio)+'%',
      time: argsAnd(flows.last_person_more_start, flows.last_person_more_end) ? flows.last_person_more_start+'-'+flows.last_person_more_end : '',

      xDataMax: calNearMax(xMaxData),
      data: personDataList2, // for biz charts

      xDatas,
      yDatas,

    };

    // 车流量
    const carDataList = [];
    for (const idx in flows.last_car_list) {
      const obj = flows.last_car_list[idx];

      // 限制数据条目为15条
      if (parseInt(idx) > 15) return;

      carDataList.push({
        x: obj.flow_date_format,
        count: obj.in_sum_now
      });
    }

    const carsTrendVO = {
      num: flows.last_car_sun || "0",
      count: flows.last_car_in || "0",
      tb: asNumber(flows.last_car_same_ratio)+'%',
      hb: asNumber(flows.last_car_surround_ratio)+'%',
      time: argsAnd(flows.last_car_more_start,flows.last_car_more_end)? flows.last_car_more_start+'-'+flows.last_car_more_end : '',

      data: carDataList
    };

    return {
      todaySummaryVO,
      todaySalesVO,
      vipsTrendVO,
      salesWarnVO,
      salesTopVO,
      salesBottomVO,
      salesTrendVO,
      salesSummaryVO,
      personsTrendVO,
      carsTrendVO,
    };
  }
}
